<template>
  <div class="spec-preview">
    <img :src="imgObj.imgUrl" />
    <div class="event" @mousemove="handler"></div>
    <div class="big">
      <img :src="imgObj.imgUrl" ref="big" />
    </div>
    <!-- 遮罩 -->
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
import { ref, getCurrentInstance, computed, onMounted } from 'vue'
export default {
  name: 'Zoom',
  props: ['skuImageList'],
  setup (props) {
    const { ctx } = getCurrentInstance()
    const instance = getCurrentInstance()
    const _this = instance.appContext.config.globalProperties
    const currenIndex = ref(0)
    const imgObj = computed(() => {
      return props.skuImageList[currenIndex.value] || {}
    }
    )
    onMounted(() => {
      _this.$mybus.on('getIndex', (idx) => {
        currenIndex.value = idx
      })
    })
    const handler = (event) => {
      // 获取照片上的图片
      const mask = ctx.$refs.mask
      // 获取鼠标移动大图
      const big = ctx.$refs.big
      // 获取鼠标中心距离左边距离
      let leftS = event.offsetX - mask.offsetWidth / 2
      // 获取鼠标中心距离上边距离
      let topS = event.offsetY - mask.offsetHeight / 2
      // 不让照片上的图片移除照片
      // 判断左边到0等于0
      if (leftS < 0) leftS = 0
      // 判断左边到最大等于最大
      if (leftS >= mask.offsetWidth) leftS = mask.offsetWidth
      // 判断高度小于0时等于0
      if (topS < 0) topS = 0
      // 判断高度大于图片高度时等于图片高度
      if (topS >= mask.offsetHeight) topS = mask.offsetHeight
      mask.style.left = leftS + 'px'
      mask.style.top = topS + 'px'
      big.style.left = -2 * leftS + 'px'
      big.style.top = -2 * topS + 'px'
    }
    return {
      currenIndex,
      handler,
      imgObj
    }
  }
}
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 600px;
  height: 359px;
  border: 1px solid #ccc;
  margin-right: 32px;
  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>
